#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
新鲜需求发现小助手
基于种子关键词扩展搜索，发现新鲜话题并发送邮件通知
"""

import logging
import time
import string
from typing import List, Dict, Set, Tuple, Optional, Any
from dataclasses import dataclass
from datetime import datetime, timedelta
from .database import DatabaseManager
from .data_sources import DataSourceManager
from .utils import (
    send_email_notification, 
    format_email_content, 
    is_fresh_topic,
    get_logger
)


@dataclass
class DiscoveryConfig:
    """新鲜需求发现配置"""
    enabled: bool = True
    similarity_threshold: float = 0.8
    max_new_topics_per_notification: int = 10
    notification_interval_hours: int = 24
    email_enabled: bool = True
    expansion_chars: List[str] = None
    
    def __post_init__(self):
        if self.expansion_chars is None:
            # 默认扩展字符：a-z, 0-9
            self.expansion_chars = list(string.ascii_lowercase) + list(string.digits)


class FreshTopicDiscovery:
    """新鲜需求发现小助手"""
    
    def __init__(self, config: Dict):
        """
        初始化新鲜需求发现小助手
        
        Args:
            config: 配置字典
        """
        self.config = config
        self.discovery_config = DiscoveryConfig(
            **config.get('fresh_topic_discovery', {})
        )
        
        # 初始化组件
        self.db_manager = DatabaseManager(config)
        self.source_manager = DataSourceManager(config)
        self.logger = get_logger("fresh_topic_discovery")
        
        # 扩展字符配置
        self.expansion_chars = self.discovery_config.expansion_chars
        
        # 记录上次通知时间
        self.last_notification_time = None
        
        self.logger.info("新鲜需求发现小助手初始化完成")
    
    def expand_seed_keywords(self, seed_keywords: List[str]) -> List[str]:
        """
        扩展种子关键词
        
        Args:
            seed_keywords: 种子关键词列表
        
        Returns:
            扩展后的关键词列表
        """
        expanded_keywords = []
        
        for seed_keyword in seed_keywords:
            # 添加原始关键词
            expanded_keywords.append(seed_keyword)
            
            # 添加扩展后的关键词
            for char in self.expansion_chars:
                expanded_keyword = seed_keyword + char
                expanded_keywords.append(expanded_keyword)
        
        self.logger.info(f"种子关键词扩展完成: {len(seed_keywords)} -> {len(expanded_keywords)}")
        return expanded_keywords
    
    def search_fresh_topics(self, seed_keywords: List[str]) -> List[Dict[str, Any]]:
        """
        搜索新鲜话题
        
        Args:
            seed_keywords: 种子关键词列表
        
        Returns:
            新鲜话题列表
        """
        self.logger.info(f"开始搜索新鲜话题，种子关键词: {len(seed_keywords)} 个")
        
        # 扩展关键词
        expanded_keywords = self.expand_seed_keywords(seed_keywords)
        
        # 获取数据库中已有的话题
        existing_topics = self._get_existing_topics()
        self.logger.info(f"数据库中已有话题: {len(existing_topics)} 个")
        
        # 搜索新话题
        all_new_topics = []
        
        for keyword in expanded_keywords:
            try:
                # 从所有数据源收集话题
                topics_with_source = self.source_manager.collect_from_all_sources(
                    keyword, 
                    with_source_info=True
                )
                
                # 转换为话题格式
                for topic_text, source_name in topics_with_source:
                    # 检查是否为新话题
                    if is_fresh_topic(
                        topic_text, 
                        existing_topics, 
                        self.discovery_config.similarity_threshold
                    ):
                        new_topic = {
                            'topic_text': topic_text,
                            'source_keyword': keyword,
                            'search_source': source_name,
                            'search_round': 1,
                            'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                            'is_fresh': True
                        }
                        all_new_topics.append(new_topic)
                        
                        # 保存到数据库
                        self.db_manager.add_topic(
                            topic_text, 
                            keyword, 
                            1
                        )
                
                # 添加延迟，避免请求过于频繁
                time.sleep(0.5)
                
            except Exception as e:
                self.logger.error(f"搜索关键词 '{keyword}' 失败: {e}")
                continue
        
        self.logger.info(f"搜索完成，发现新鲜话题: {len(all_new_topics)} 个")
        return all_new_topics
    
    def _get_existing_topics(self) -> List[str]:
        """
        获取数据库中已有的话题
        
        Returns:
            已有话题列表
        """
        try:
            # 这里需要根据实际的数据库结构来获取话题
            # 暂时返回空列表，实际使用时需要实现
            return []
        except Exception as e:
            self.logger.error(f"获取已有话题失败: {e}")
            return []
    
    def should_send_notification(self) -> bool:
        """
        判断是否应该发送通知
        
        Returns:
            是否应该发送通知
        """
        if not self.discovery_config.email_enabled:
            return False
        
        if self.last_notification_time is None:
            return True
        
        # 检查是否超过通知间隔
        time_since_last = datetime.now() - self.last_notification_time
        return time_since_last >= timedelta(hours=self.discovery_config.notification_interval_hours)
    
    def send_fresh_topic_notification(
        self, 
        new_topics: List[Dict[str, Any]], 
        search_keyword: str = "种子关键词",
        search_round: int = 1
    ) -> bool:
        """
        发送新鲜话题通知
        
        Args:
            new_topics: 新鲜话题列表
            search_keyword: 搜索关键词
            search_round: 搜索轮数
        
        Returns:
            是否发送成功
        """
        if not new_topics:
            self.logger.info("没有新鲜话题，无需发送通知")
            return False
        
        if not self.should_send_notification():
            self.logger.info("距离上次通知时间过短，跳过通知")
            return False
        
        try:
            # 限制通知中的话题数量
            topics_to_notify = new_topics[:self.discovery_config.max_new_topics_per_notification]
            
            # 格式化邮件内容
            email_content = format_email_content(
                topics_to_notify, 
                search_keyword, 
                search_round
            )
            
            # 发送邮件
            subject = f"🎯 发现 {len(topics_to_notify)} 个新鲜话题！"
            success = send_email_notification(
                subject, 
                email_content, 
                self.config
            )
            
            if success:
                self.last_notification_time = datetime.now()
                self.logger.info(f"新鲜话题通知发送成功: {len(topics_to_notify)} 个话题")
            else:
                self.logger.error("新鲜话题通知发送失败")
            
            return success
            
        except Exception as e:
            self.logger.error(f"发送新鲜话题通知失败: {e}")
            return False
    
    def run_discovery_cycle(
        self, 
        seed_keywords: List[str], 
        auto_notify: bool = True
    ) -> Dict[str, Any]:
        """
        运行一个完整的发现周期
        
        Args:
            seed_keywords: 种子关键词列表
            auto_notify: 是否自动发送通知
        
        Returns:
            发现结果统计
        """
        self.logger.info("开始运行新鲜需求发现周期")
        
        start_time = time.time()
        
        try:
            # 搜索新鲜话题
            new_topics = self.search_fresh_topics(seed_keywords)
            
            # 统计结果
            result_stats = {
                'total_seed_keywords': len(seed_keywords),
                'total_expanded_keywords': len(seed_keywords) * (1 + len(self.expansion_chars)),
                'new_topics_found': len(new_topics),
                'discovery_time': time.time() - start_time,
                'timestamp': datetime.now().isoformat()
            }
            
            # 自动发送通知
            if auto_notify and new_topics:
                notification_sent = self.send_fresh_topic_notification(
                    new_topics, 
                    f"{len(seed_keywords)}个种子关键词", 
                    1
                )
                result_stats['notification_sent'] = notification_sent
            
            self.logger.info(f"发现周期完成: {result_stats}")
            return result_stats
            
        except Exception as e:
            self.logger.error(f"发现周期执行失败: {e}")
            return {
                'error': str(e),
                'timestamp': datetime.now().isoformat()
            }
    
    def get_discovery_statistics(self) -> Dict[str, Any]:
        """
        获取发现统计信息
        
        Returns:
            统计信息字典
        """
        try:
            stats = {
                'total_topics': self.db_manager.get_topic_count(),
                'total_keywords': self.db_manager.get_keyword_count(),
                'last_notification_time': self.last_notification_time.isoformat() if self.last_notification_time else None,
                'expansion_chars_count': len(self.expansion_chars),
                'similarity_threshold': self.discovery_config.similarity_threshold,
                'notification_interval_hours': self.discovery_config.notification_interval_hours
            }
            return stats
        except Exception as e:
            self.logger.error(f"获取统计信息失败: {e}")
            return {'error': str(e)}
    
    def cleanup(self):
        """清理资源"""
        try:
            if self.db_manager:
                self.db_manager.close()
            self.logger.info("新鲜需求发现小助手资源清理完成")
        except Exception as e:
            self.logger.error(f"资源清理失败: {e}")


class FreshTopicDiscoveryScheduler:
    """新鲜需求发现调度器"""
    
    def __init__(self, config: Dict):
        """
        初始化调度器
        
        Args:
            config: 配置字典
        """
        self.config = config
        self.discovery = FreshTopicDiscovery(config)
        self.logger = get_logger("discovery_scheduler")
        self.running = False
    
    def start_scheduled_discovery(
        self, 
        seed_keywords: List[str], 
        interval_hours: int = 24
    ):
        """
        启动定时发现任务
        
        Args:
            seed_keywords: 种子关键词列表
            interval_hours: 发现间隔（小时）
        """
        self.running = True
        self.logger.info(f"启动定时发现任务，间隔: {interval_hours} 小时")
        
        try:
            while self.running:
                # 运行发现周期
                result = self.discovery.run_discovery_cycle(seed_keywords)
                
                if 'error' not in result:
                    self.logger.info(f"定时发现完成: {result}")
                else:
                    self.logger.error(f"定时发现失败: {result}")
                
                # 等待下次执行
                if self.running:
                    self.logger.info(f"等待 {interval_hours} 小时后执行下次发现...")
                    time.sleep(interval_hours * 3600)
                    
        except KeyboardInterrupt:
            self.logger.info("收到中断信号，停止定时发现任务")
        except Exception as e:
            self.logger.error(f"定时发现任务异常: {e}")
        finally:
            self.stop_scheduled_discovery()
    
    def stop_scheduled_discovery(self):
        """停止定时发现任务"""
        self.running = False
        self.logger.info("定时发现任务已停止")
        self.discovery.cleanup()
